package edu.bu.trident.k9scheduler.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Trident_K9Scheduler implements EntryPoint {

	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Button sendButton = new Button("Login");
		final TextBox nameField = new TextBox();
		final PasswordTextBox passwordField = new PasswordTextBox();
		final Label errorLabel = new Label();

		final TextBox zipField = new TextBox();
		final TextBox cityField = new TextBox();
		final TextBox stateField = new TextBox();

		final Button searchButton = new Button("Search");

		//
		nameField.setText("izhuravlova@gmail.com");
		passwordField.setText("tip*NOW*pls123");
		//
		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		RootPanel.get("alreadyMember").add(new Label("Already a member?"));
		RootPanel.get("nameLabelContainer").add(new Label("User name:"));
		RootPanel.get("nameFieldContainer").add(nameField);
		RootPanel.get("passwordLabelContainer").add(new Label("Password:"));
		RootPanel.get("passwordFieldContainer").add(passwordField);
		RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);

		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class LoginHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				login();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					login();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void login() {
				// First, we validate the input.
				String userName = nameField.getText();
				String password = passwordField.getText();

				boolean validate = errorCheckUsernamePassword(userName,
						password);

				if (!validate) {
					errorLabel
							.setText("Please enter valid user name and password");
					return;
				} else {
					errorLabel.setText("");
				}

				String textToServer = userName + " " + password;

				// Then, we send the input to the server.
				sendButton.setEnabled(false);
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");
				greetingService.greetServer(textToServer,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox
										.setText("Remote Procedure Call - Failure");
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								//
								RootPanel.get("alreadyMember").clear();
								RootPanel.get("nameLabelContainer").clear();
								RootPanel.get("nameFieldContainer").clear();
								RootPanel.get("passwordLabelContainer").clear();
								RootPanel.get("passwordFieldContainer").clear();
								RootPanel.get("sendButtonContainer").clear();
								RootPanel.get("errorLabelContainer").clear();

								RootPanel
										.get("locateDegWalkerLabelContainer")
										.add(new Label(
												"Locate Dog Walker in your area"));
								RootPanel.get("zipLabelContainer").add(
										new Label("Enter Zip Code:"));
								RootPanel.get("zipFieldContainer")
										.add(zipField);
								RootPanel.get("orLabelContainer").add(
										new Label("or"));
								RootPanel.get("cityLabelContainer").add(
										new Label("Enter City:"));
								RootPanel.get("cityFieldContainer").add(
										cityField);
								RootPanel.get("stateLabelContainer").add(
										new Label("Enter State:"));
								RootPanel.get("stateFieldContainer").add(
										stateField);
								RootPanel.get("searchDogWalkerContainer").add(
										searchButton);
								//
								dialogBox.setText("Remote Procedure Call");
								serverResponseLabel
										.removeStyleName("serverResponseLabelError");
							}
						});
			}
		}

		class SearchHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				search();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					search();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void search() {
				String zip = zipField.getText().trim();
				String city = cityField.getText().trim();
				String state = stateField.getText().trim();

				if (zip.length() == 0
						&& (city.length() == 0 && state.length() == 0)) {
					errorLabel
							.setText("Please enter valid zip code or city and state");
					return;
				} else {
					errorLabel.setText("");
				}

				String textToServer = zip + "&" + city + "&" + state;

				greetingService.searchDogWalkers(textToServer,
						new AsyncCallback<String[]>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox
										.setText("Remote Procedure Call - Failure");
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String[] result) {

								RootPanel.get("dogWalkerContainer1").clear();

								for (int i = 0; i < result.length; i++) {
									String dogWalker = result[i];
									int dogWalkerIndex = dogWalker.indexOf("&");
									String dogWalkerTitle = dogWalker
											.substring(0, dogWalkerIndex);
									String dogWalkerTestemonial = dogWalker
											.substring(dogWalkerIndex + 1);
									DisclosurePanel dogWalkerDisclosurePanel = new DisclosurePanel(
											dogWalkerTitle);
									HTML dogWalkerTestemonialHtml = new HTML();
									dogWalkerTestemonialHtml.setHTML("<p>"
											+ dogWalkerTestemonial + "</p>");
									dogWalkerDisclosurePanel
											.setContent(dogWalkerTestemonialHtml);
									RootPanel.get("dogWalkerContainer1").add(
											dogWalkerDisclosurePanel);
								}
							}
						});
			}
		}

		// Add a handler to send the name to the server
		LoginHandler loginHandler = new LoginHandler();
		sendButton.addClickHandler(loginHandler);
		nameField.addKeyUpHandler(loginHandler);

		SearchHandler searchHandler = new SearchHandler();
		searchButton.addClickHandler(searchHandler);
	}

	private boolean errorCheckUsernamePassword(String username, String password) {

		// make sure not null
		if (username.isEmpty() || password.isEmpty())
			return false;

		// make sure not longer than 320
		if (username.length() > 320)
			return false;

		// make sure not longer than 30 or less than 3
		if (password.length() > 30 || password.length() < 4)
			return false;

		// make sure username and password do not match
		if (username == password)
			return false;

		// make sure there is only one '@' symbol
		int ndx_start = username.indexOf('@');
		int ndx_end = username.lastIndexOf('@');
		if (ndx_start == ndx_end && ndx_start != -1) {
			// break the string into local and domain
			String local = username.substring(0, ndx_start);
			String domain = username.substring(ndx_start + 1);

			// check local length is not greater than 64
			if (local.length() > 64)
				return false;

			// check domain length 255
			if (domain.length() > 255)
				return false;
		}

		if (password.compareToIgnoreCase("welcome") == 0
				|| password.compareToIgnoreCase("database") == 0
				|| password.compareToIgnoreCase("account") == 0
				|| password.compareToIgnoreCase("user") == 0
				|| password.compareToIgnoreCase("password") == 0
				|| password.compareToIgnoreCase("oracle") == 0
				|| password.compareToIgnoreCase("computer") == 0
				|| password.compareToIgnoreCase("abcd") == 0)
			return false;

		return true;
	}
}
